<!--部门-->
<!--chenyi 2019-10-12 22:13:52-->
<template>
  <div @mousewheel="handleTabWheel" style="width: 100%;height: 100%;">
    <el-button-group v-show="displayType==='tree'" style="margin-left: 10px;float:left">
      <el-button  @click="getTreeData" type="primary" icon="el-icon-refresh">刷新数据
      </el-button>
      <el-button  v-show="horizontal" type="primary" @click="horizontal=!horizontal" icon="el-icon-sort">切换布局
      </el-button>
      <el-button v-show="!horizontal" type="primary" @click="horizontal=!horizontal" icon="el-icon-sort">切换布局
      </el-button>
    </el-button-group>
    <el-button-group style="margin-right: 10px;float:right">
      <el-button :type="displayType==='list'?'primary':''" @click="displayType='list'" icon="el-icon-tickets">列表展示
      </el-button>
      <el-button :type="displayType==='tree'?'primary':''" @click="displayType='tree'" icon="el-icon-s-data">树形展示
      </el-button>
    </el-button-group>
    <div v-show="displayType==='tree'" class="tree-wrapper"
         :style="'transform: translate(-50%, -50%) scale('+zoomHandled+','+zoomHandled+');'" >
      <org-tree
        :data="treeData[0]"
        collapsable
        :node-render="nodeRender"
        :expand-all="expandAll"
        :horizontal="horizontal"
        :props="props"
        ></org-tree>
    </div>

    <div v-show="displayType==='list'">
      <!--搜索条件-->
      <el-form inline :model="searchParam" ref="searchParam" label-width="80px" class="search-form">
        <el-form-item label="部门编码" prop="deptCodeVague">
          <el-input v-model="searchParam.deptCodeVague" placeholder="请输入部门编码" clearable></el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="deptNameVague">
          <el-input v-model="searchParam.deptNameVague" placeholder="请输入部门名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="上级部门" prop="parentId">
          <es-tree v-model="searchParam.parentId" expand-root url="/admin/dept/treeData"></es-tree>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="searchForm">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetSearchForm">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row>
        <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
        <el-button type="primary" icon="el-icon-edit" @click="edit">修改</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="handleDelete">删除</el-button>
      </el-row>
      <!--表格-->
      <el-table
        border
        :data="tableData"
        v-loading="loading"
        element-loading-text="数据加载中"
        @selection-change="handleSelectionChange"
        class="mt-20">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>

        <el-table-column
          prop="deptCode"
          label="部门编号"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column
          prop="deptName"
          label="部门名称"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column
          prop="parentName"
          label="上级部门"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <!--自定义组件 字典转义-->
            {{scope.row.parentName||'易选网络'}}
          </template>
        </el-table-column>

        <el-table-column
          prop="sortNo"
          label="排序"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column
          prop="isSys"
          label="是否系统内置"
          width="150">
          <template slot-scope="scope">
            <!--自定义组件 字典转义-->
            <es-value-format
              enum-name="WhetherEnum"
              :value="scope.row.isSys"
              render-color>
            </es-value-format>
          </template>
        </el-table-column>

        <el-table-column
          prop="status"
          label="状态"
          width="150">
          <template slot-scope="scope">
            <!--自定义组件 字典转义-->
            <es-value-format
              enum-name="StatusEnum"
              :value="scope.row.status"
              render-color>

            </es-value-format>
          </template>
        </el-table-column>

        <el-table-column
          fixed="right"
          label="操作"
          show-overflow-tooltip
          width="250">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="detail(scope.row)">查看
            </el-button>
            <el-button
              size="mini" type="primary"
              @click="edit(scope.$index, scope.row)">编辑
            </el-button>
            <el-button
              v-if="scope.row.isSys == 0"
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>

          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-pagination
        style="margin: 20px;float: right;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-size="searchParam.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!--新增修改-->
      <el-dialog :title="title" :visible="action==='add' || action==='edit'" :before-close="handleClose">
        <el-form :model="item" :rules="rules" ref="ruleForm" label-width="100px">
          <div class="form-item-group">

            <el-form-item label="部门编号" prop="deptCode">
              <el-input v-model="item.deptCode"
                        placeholder="请输入部门编号"
                        maxlength="10"
                        show-word-limit
                        :disabled="action === 'edit'"
              ></el-input>
            </el-form-item>
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="item.deptName"
                        placeholder="请输入部门名称"
                        maxlength="50"
                        show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="上级部门" prop="parentId">
              <es-tree v-model="item.parentId" expand-root :data="treeData"></es-tree>
            </el-form-item>

            <el-form-item label="排序" prop="sortNo">
              <el-input v-model="item.sortNo"
                        placeholder="请输入排序"
                        maxlength="50"
                        show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="item.remark"
                        placeholder="请输入备注"
                        maxlength="50"
                        show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <es-select v-model="item.status" enum-name="StatusEnum"></es-select>
            </el-form-item>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="action = 'list'">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>

      <!--详情页-->
      <el-dialog :title="title" :visible="action==='info'" :before-close="handleClose">
        <el-form :model="item" label-width="100px">
          <div class="form-item-group">
            <el-form-item label="部门编号" prop="deptCode">
              <span>{{item.deptCode||"-"}}</span>
            </el-form-item>
            <el-form-item label="部门名称" prop="deptName">
              <span>{{item.deptName||"-"}}</span>
            </el-form-item>
            <el-form-item label="上级部门" prop="parentId">
              <es-value-format :data="treeData" :value="item.parentId"></es-value-format>
            </el-form-item>
            <el-form-item label="排序" prop="sortNo">
              <span>{{item.sortNo||"-"}}</span>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <span>{{item.remark||"-"}}</span>
            </el-form-item>
            <el-form-item label="状态:">
              <es-value-format enum-name="StatusEnum" :value="item.status" render-color></es-value-format>
            </el-form-item>
            <el-form-item label="是否系统内置" prop="isSys">
              <value-format enum-name="WhetherEnum" :value="item.isSys" render-color></value-format>
            </el-form-item>


          </div>
          <div class="form-item-group">

          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="action = 'list'">关闭</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>
  import {getList, save, update, remove, treeData} from '../../api/sys/deptApi'
  import validate from '../../libs/validate'
  import OrgTree from 'v-org-tree'
  import 'v-org-tree/dist/v-org-tree.css'

  export default {
    name: 'dept',
    components: {
      OrgTree
    },
    data() {
      return {
        searchParam: {//表格数据请求参数
          page: 1,
          limit: 10
        },
        title: '',
        action: 'list',
        loading: false,
        item: {},  //修改/详情数据
        rules: {  //表单验证
          deptCode: [
            {required: true, message: '请输入部门编号', trigger: 'blur'}
          ],
          deptName: [
            {required: true, message: '请输入部门名称', trigger: 'blur'}
          ],
          sortNo: [
            {required: true, message: '请输入排序', trigger: 'blur'},
            {validator: validate.integer, trigger: 'blur'}
          ],
          parentId: [
            {required: true, message: '请选择上级部门', trigger: 'blur'}
          ],
          status: [
            {required: true, message: '请选择状态', trigger: 'change'}
          ]
        },
        multipleSelection: [], //复选框选中的值
        tableData: [],
        total: 0,
        ids: [],
        treeData: [],
        props: {
          id: 'value',
          label: 'label',
          children: 'children'
        },
        displayType: "list",
        expandAll: true,
        horizontal:true,//是否横向展示
        zoomHandled:1
      }
    },
    created() {
      this.getTreeData();
    },
    mounted() {
      //获取数据
      this.getTableData();
    },
    methods: {
      //tree滚轮监听
      handleTabWheel: function (e) {
        if(this.displayType==="list"){return false;}
        let wheelDelta = e.wheelDelta;
        if(wheelDelta<0){
            this.zoomHandled=this.zoomHandled-0.2<=0?0:this.zoomHandled-0.2;
        }else if(wheelDelta>0){
           this.zoomHandled=this.zoomHandled+0.2>=1?1:this.zoomHandled+0.2;
        }
      },
      nodeRender(h, data) {
        return (
          <div class="custom-org-node">{data.label}</div>
      )
      },
      getTreeData(){
        let _this = this;
        treeData().then(res => {
          if (res.code === 200) {
            _this.treeData = res.data;
          }
        });
      },
      //获取数据
      getTableData() {
        let _this = this
        _this.loading = true
        getList(_this.searchParam).then((res) => {
          if (res.code === 200) {
            _this.tableData = res.data
            console.log(_this.tableData)
            _this.total = res.total
          } else {
            this.$message.error(res.msg)
          }
          _this.loading = false
        })
      },
      //提交表单
      submitForm() {
        let _this = this
        _this.$refs['ruleForm'].validate(function (valid) {
          if (valid) {
            //保存
            if (_this.action === 'add') {
              save(_this.item).then((res) => {
                if (res.code === 200) {
                  _this.$message.success('新增成功！');
                  _this.getTableData();
                  _this.action = 'list';
                } else {
                  _this.$message.error(res.msg);
                }

              })
            }
            //修改
            else if (_this.action === 'edit') {
              update(_this.item).then((res) => {
                if (res.code === 200) {
                  _this.$message.success('修改成功！')
                  _this.getTableData()
                } else {
                  _this.$message.error(res.msg)
                }
                _this.action = 'list'
              })
            }
          }
        })
      },
      //删除
      handleDelete: function (index, row) {
        let temp = Object.assign({}, row);
        //获取选中的id
        let ids = this.getSelectIds(temp);
        if (ids.length > 0) {
          this.ids = ids;
          //删除数据
          let _this = this;
          _this.$confirm('如有下级部门将移动至顶级部门下，是否继续删除?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            callback: function (action, instance) {
              if (action === "confirm") {
                remove(_this.ids).then((res) => {
                  if (res.code === 200) {
                    //刷新表格数据
                    _this.getTableData();
                    _this.$message.success("删除成功!");
                  }
                  else {
                    _this.$message.error(res.msg);
                  }
                })
                ;
              }
            }
          })
        }
      },
      add() {
        this.item = {}
        this.action = 'add'
        this.title = '新增部门'
      },
      //修改页面
      edit: function (index, row) {
        let _this = this
        let temp = Object.assign({}, row)
        if (Object.keys(temp).length === 0) {
          let chcekeds = _this.multipleSelection
          if (chcekeds.length === 0) {
            _this.$message.error('请选择一条数据')
            return false
          } else if (chcekeds.length > 1) {
            _this.$message.error('只能选择一条数据')
            return false
          } else {
            _this.item = chcekeds[0]
          }
        } else {
          _this.item = temp
        }
        _this.action = 'edit'
        _this.title = '修改部门'
        _this.currentIndex = index;
      },
      detail(row) {
        this.item = row;
        this.action = 'info';
      },
      handleClose(done) {
        this.action = 'list'
        done()
      },
      //获取选中行
      getSelectIds: function (row) {
        let chcekeds = [];
        let ids = [];
        if (!row || Object.keys(row).length === 0) {
          chcekeds = this.multipleSelection;
          if (chcekeds.length === 0) {
            this.$message.error("至少选择一条数据");
          } else {
            for (let key in chcekeds) {
              ids.push(chcekeds[key].id);
            }
          }
        } else {
          ids.push(row.id);
        }
        return ids;

      },
      //查询表格
      searchForm() {
        this.searchParam.page = 1
        //获取数据
        this.getTableData()
      },
      //重置查询表格
      resetSearchForm() {
        this.$refs['searchParam'].resetFields()
        //获取数据
        this.getTableData()
      },
      handleSizeChange(limit) {
        this.searchParam.limit = limit
        //获取数据
        this.getTableData()
      },
      handleCurrentChange(page) {
        this.searchParam.page = page
        //获取数据
        this.getTableData()
      },
      //复选框选择
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
    }
  }
</script>

<style lang="less">
  .tree-wrapper{
    position: absolute;
    left: 50%;
    top: 50%;
  }
  .custom-org-node {
    padding: 14px 41px;
    background: #738699;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    white-space: nowrap;
    border-radius: 4px;
    color: #fff;
    font-size: 14px;
    font-weight: 500;
    line-height: 20px;
    -webkit-transition: background .1s ease-in;
    transition: background .1s ease-in;
    cursor:pointer;
  }
</style>
